package cn.jdx.shiro;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Collection;
import java.util.Set;

public class RedisCacheManager implements CacheManager {

    private RedisTemplate redisTemplate;

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public <K, V> Cache<K, V> getCache(String s) throws CacheException {
        return new RedisCache<K,V>();
    }

    //自定义一个内部类实现Cache
    class RedisCache<K,V> implements Cache<K,V>{

        private final static String CACHE_KEY = "redis_cache";

        @Override
        public V get(K k) throws CacheException {
            return (V)redisTemplate.boundHashOps(CACHE_KEY).get(k);
        }

        @Override
        public V put(K k, V v) throws CacheException {
            redisTemplate.boundHashOps(CACHE_KEY).put(k,v);
            return v;
        }

        @Override
        public V remove(K k) throws CacheException {
            V v = get(k);//调用重写的get方法
            redisTemplate.boundHashOps(CACHE_KEY).delete(k);
            return null;
        }

        @Override
        public void clear() throws CacheException {
            redisTemplate.delete(CACHE_KEY);
        }

        @Override
        public int size() {
            Long size = redisTemplate.boundHashOps(CACHE_KEY).size();
            return size.intValue();
        }

        @Override
        public Set<K> keys() {
            return redisTemplate.boundHashOps(CACHE_KEY).keys();
        }

        @Override
        public Collection<V> values() {
            return redisTemplate.boundHashOps(CACHE_KEY).values();
        }
    }
}
